package cn.cqs.redisitem.shiro;
/**
 * @discription :
 * @author: cqs
 * @date: 2020-09-11 13:23
 */

import cn.cqs.redisitem.utils.AES.JwtUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class JwtShiroFilter extends BasicHttpAuthenticationFilter {
    //    是否刷新token(默认为false)
    private boolean refreshToken;

    public JwtShiroFilter() {
        this.refreshToken = false;
    }


    public boolean isRefreshToken() {
        return refreshToken;
    }

    public void setRefreshToken(boolean refreshToken) {
        this.refreshToken = refreshToken;
    }

    /**
     * 功能描述 :设置跨区支持
     *
     * @param request:
     * @param response:
     * @return void
     * @author cqs
     * @date 2020/9/11
     */

    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setStatus(HttpStatus.OK.value());
        }
    }

    /**
     * 功能描述 :请求是否允许放行
     * 父类会在请求进入拦截器后调用该方法，返回true则继续，返回false则会调用onAccessDenied()。
     * 这里在不通过时，还调用了isPermissive()方法，
     *
     * @param request:
     * @param response:
     * @param mappedValue:
     * @return boolean
     * @author cqs
     * @date 2020/9/11
     */

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        boolean flag = false;
        try {
            flag = executeLogin(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag && super.isPermissive(mappedValue);
    }

    /**
     * 功能描述 :如果Filter在之前isAccessAllowed（）方法中返回false,则会进入这个方法。
     * 我们这里直接返回错误的response
     *
     * @param request:
     * @param response:
     * @return boolean
     * @author cqs
     * @date 2020/9/11
     */

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
//        webUtils工具将servertrequest或servertreposel转HttpServerletRequest或httpServletRepose
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        String token = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isNotBlank(token)) {
            JwtToken jwtToken = new JwtToken(token);
//            委托 realm 进行登录认证(交给自定义realm进行jwt验证和对应角色,权限的查询)
            try {
                this.getSubject(request, response).login(jwtToken);
            } catch (AuthenticationException e) {
                e.printStackTrace();
                onLoginFail(request, response);
            }

        }


//        fillCorsHeader(request, httpServletResponse);
        return true;
    }

    /**
     * 功能描述 :登录成功后是否刷新token
     *
     * @param token:
     * @param subject:
     * @param request:
     * @param response:
     * @return boolean
     * @author cqs
     * @date 2020/9/11
     */

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        String oldToken = token.getPrincipal().toString();
        Date expireAt = JwtUtils.getExpairtion(oldToken);
        Long now = System.currentTimeMillis();
        Long remainingTime = now - expireAt.getTime();
//        过期时间不足10分钟
        if (refreshToken && ObjectUtils.isNotEmpty(expireAt) && remainingTime < 600000) {
//            UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
//            User user = (User) subject.getPrincipal();
//            String newToken = userService.generateJwt(user.getUsername());

            HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
//            httpServletResponse.setHeader("token",newtoken);
        }
        return super.onLoginSuccess(token, subject, request, response);
    }

    /**
     * 功能描述 :创建token
     *
     * @param request:
     * @param response:
     * @return org.apache.shiro.authc.AuthenticationToken
     * @author cqs
     * @date 2020/9/11
     */

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
//        请求头中获取token
        String token = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            // 从请求头中的token字段（自定义字段）尝试获取jwt token
            token = httpServletRequest.getHeader("token");
        }
        if (StringUtils.isEmpty(token)) {
            // 从url参数中尝试获取jwt token
            token = httpServletRequest.getParameter("token");
        }

        if (!StringUtils.isEmpty(token)) {
            return new JwtToken(token);
        }


        return super.createToken(request, response);
    }

    /**
     * 功能描述 :登录失败处理
     *
     * @param token:
     * @param e:
     * @param request:
     * @param response:
     * @return boolean
     * @author cqs
     * @date 2020/9/11
     */

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        try {
            onLoginFail(request, response);
        } catch (IOException ex) {
            ex.printStackTrace();

        }
        return false;
    }

    private void onLoginFail(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setStatus(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value());
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write("token 444".getBytes());
//       备注outputStream中的print()只能输入英文,不能输入中文
//   outputStream.print("No Token");
        outputStream.flush();
        outputStream.close();
//        PrintWriter printWriter = httpServletResponse.getWriter();
//        printWriter.write("token无效");
//        printWriter.flush();
//        printWriter.close();

//        HttpServletResponse httpResponse = (HttpServletResponse) response;
//        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//        httpResponse.getWriter().write("login error");
    }

    /**
     * 功能描述 :获取token判断
     *
     * @param request:
     * @return java.lang.String
     * @author cqs
     * @date 2020/9/11
     */

    public String getToken(ServletRequest request) {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
//        //从header中获取token
        String token = httpServletRequest.getHeader("token");
        if (StringUtils.isBlank(token)) {
//           从header中获取参数为：Authorization
            token = httpServletRequest.getHeader("Authorization");
        }
        if (StringUtils.isBlank(token)) {
            //如果header中不存在token，则从参数中获取token
            token = httpServletRequest.getParameter("token");
        }
        return token;
    }

}
